package com.controller.backend.news;

import com.util.DataSourceUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Objects;

@WebServlet("/update_news")
public class UpdateNewsServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id = Integer.parseInt(req.getParameter("nid"));
        String newTitle = req.getParameter("title");
        String newContent = req.getParameter("content");
        String type = req.getParameter("ntype");
//        String sql = "update notifications set title=?,content=?,add_time=? where id=?";
        String sql = "update news set title=?,content=? where id=?";
        try(Connection conn = DataSourceUtils.getConnection();
            PreparedStatement st = conn.prepareStatement(sql)) {
            st.setString(1, newTitle);
            st.setString(2, newContent);
            st.setInt(3, id);
            st.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
//        System.out.println(type);
        if (Objects.equals(type, "学院新闻")) {
            resp.sendRedirect(req.getContextPath()+"/backend/news/college");
        } else if (Objects.equals(type, "党建工作")) {
            resp.sendRedirect(req.getContextPath()+"/backend/news/party");
        } else if (Objects.equals(type, "学团动态")) {
            resp.sendRedirect(req.getContextPath()+"/backend/news/group");
        }
    }
}
